package voja.android.crvenazvezda;

import android.R.color;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

public class LiveWallpaperPainting extends Thread {
	
	private SurfaceHolder surfaceHolder;
	private Context context;
	private Boolean wait = false, run = true;
	private int width, height;
	private long previousTime, currentTime, _timeout;
	int iteration=0;
	
	LiveWallpaperPainting(SurfaceHolder surfaceHolder, Context context) {
		this.surfaceHolder = surfaceHolder;
		this.context = context;
		this.wait = true;
		
		_timeout = 5;
	}
	
	public void pausePainting() {
		this.wait = true;
		synchronized(this) {
			this.notify();
		}
	}
 
	public void resumePainting() {
		this.wait = false;
		synchronized(this) {
			this.notify();
		}
	}
 
	public void stopPainting() {
		this.run = false;
		synchronized(this) {
			this.notify();
		}
	}
 
	public void run() {
		this.run = true;
		Canvas c = null;
		while (run) {
			try {
				c = this.surfaceHolder.lockCanvas(null);
				synchronized (this.surfaceHolder) {
					currentTime = System.currentTimeMillis();
					//updatePhysics();
					doDraw(c);
					iteration++;
					previousTime = currentTime;
				}
			} finally {
				if (c != null) {
					this.surfaceHolder.unlockCanvasAndPost(c);
				}
			}
			// pause if no need to animate
			synchronized (this) {
				if (wait) {
					try {
						wait();
					} catch (Exception e) {}
				}
			}
		}
	}
 
	public void setSurfaceSize(int width, int height) {
		this.width = width;
		this.height = height;
		synchronized(this) {this.notify();}
	}
 
	public void doTouchEvent(MotionEvent event) {
		// handle the event here
		// if there is something to animate
		// then wake up
		/*this.wait = false;
		synchronized(this) {
			notify();
		}*/
	}
 
	private void doDraw(Canvas canvas) {
		Paint p = new Paint();
		p.setTextSize(30);
		p.setColor(Color.WHITE);
		canvas.drawText("Voja"+iteration, 10, 10, p);
		/*
		Bitmap _scratch = BitmapFactory.decodeResource(context.getResources(), R.drawable.grass);
		canvas.drawBitmap(_scratch, 0, 0, null);
		*/
	}
 
	private void updatePhysics() {
		// if nothing was updated :
		this.wait = true;
	}
	
}
